package com.carambatv.android.ui.sliding;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.carambatv.android.R;
import com.carambatv.android.adapter.GridAdapter;
import com.carambatv.android.db.ChannelColumns;
import com.carambatv.android.db.ChannelQuery;
import com.carambatv.android.model.ChannelObject;
import com.carambatv.android.service.UpdateChannelService;
import com.carambatv.android.ui.feed.FeedFragment;
import com.carambatv.android.utils.Config;
import com.carambatv.android.utils.DetachableResultReceiver;
import com.carambatv.android.utils.DetachableResultReceiver.Receiver;

public class GridFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {

	private GridAdapter mAdapter;
	private DetachableResultReceiver receiver;
	public static final int SHOW_INIT_LIST = 11;
	public static final int RATE_ME = 2;
	public static final int ORDER_BY_ALPHABET = 3;
	public static final int ORDER_BY_SUBSCRIBERS = 4;
	public static final String ORDER = "order";
	private GridView gridView;
	private SharedPreferences prefs = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View root = inflater.inflate(R.layout.grid_fragment, container, false);

		gridView = (GridView) root.findViewById(R.id.grid_layout);
		gridView.setOnItemClickListener(this);

		return root;
	}

	@Override
	public void onResume() {
		super.onResume();
		getSherlockActivity().getSupportActionBar().setTitle(R.string.app_name);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mAdapter = new GridAdapter(getActivity(), null);
		gridView.setAdapter(mAdapter);

		Bundle bundle = new Bundle();
		bundle.putString(ORDER, prefs.getString(ORDER, ChannelObject.SUBSCRIBERS_SORT));
		getActivity().getSupportLoaderManager().initLoader(SHOW_INIT_LIST, bundle, this);

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(receiverUpdate);

		for (int i = 0; i < Config.arrayChannels.length; i++) {
			Intent upfateIntent = new Intent(Intent.ACTION_SYNC, null, getActivity(), UpdateChannelService.class);
			upfateIntent.putExtra(UpdateChannelService.EXTRA_STATUS_RECEIVER, receiver);
			upfateIntent.putExtra(UpdateChannelService.EXTRA_REQUEST_CODE, Config.YTUBE);
			upfateIntent.putExtra(Config.TYPE, Config.arrayChannels[i]);
			getActivity().startService(upfateIntent);
		}

	}

	private Receiver receiverUpdate = new Receiver() {
		@Override
		public void onReceiveResult(int resultCode, Bundle resultData) {
		}
	};

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		menu.add(0, RATE_ME, 0, R.string.rate_me).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

		SubMenu subMenu1 = menu.addSubMenu("");
		subMenu1.add(0, ORDER_BY_SUBSCRIBERS, 0, R.string.order_by_subscraibers);
		subMenu1.add(0, ORDER_BY_ALPHABET, 0, R.string.order_by_alphabet);

		MenuItem subMenu1Item = subMenu1.getItem();
		subMenu1Item.setIcon(android.R.drawable.ic_menu_sort_by_size);
		subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		super.onCreateOptionsMenu(menu, inflater);
	};

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Bundle bundle = null;
		final Editor edit = prefs.edit();
		switch (item.getItemId()) {
		case ORDER_BY_ALPHABET:

			edit.putString(ORDER, ChannelObject.ALPHABET_SORT);
			edit.commit();

			bundle = new Bundle();
			bundle.putString(ORDER, ChannelObject.ALPHABET_SORT);
			getActivity().getSupportLoaderManager().restartLoader(SHOW_INIT_LIST, bundle, this);
			return true;
		case ORDER_BY_SUBSCRIBERS:

			edit.putString(ORDER, ChannelObject.SUBSCRIBERS_SORT);
			edit.commit();

			bundle = new Bundle();
			bundle.putString(ORDER, ChannelObject.SUBSCRIBERS_SORT);
			getActivity().getSupportLoaderManager().restartLoader(SHOW_INIT_LIST, bundle, this);
			return true;
		case RATE_ME:
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setData(Uri.parse("market://details?id=com.carambatv.android"));
			try {
				startActivity(intent);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public Loader<Cursor> onCreateLoader(int token, Bundle bundle) {
		String order_by = bundle.getString(ORDER);
		return new CursorLoader(getActivity(), ChannelObject.CONTENT_URI, ChannelQuery.PROJECTION, null, null, order_by);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> lader, Cursor newCursor) {
		mAdapter.swapCursor(newCursor);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {
		mAdapter.swapCursor(null);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
		Cursor mCursor = mAdapter.getCursor();
		if (mCursor.moveToPosition(position)) {

			String title = mCursor.getString(mCursor.getColumnIndex(ChannelColumns.TITLE.getName()));
			String type = mCursor.getString(mCursor.getColumnIndex(ChannelColumns.ID_CHANNEL.getName()));

			Fragment mFragment = VideoFragment.newInstance(type, title);
			FragmentManager fm = getActivity().getSupportFragmentManager();
			FragmentTransaction transaction = fm.beginTransaction();
			transaction.hide(GridFragment.this);
			transaction.replace(R.id.grid_fragment, mFragment);
			transaction.addToBackStack(FeedFragment.class.getSimpleName());
			transaction.commit();
		}

	}

}
